package com.maxjay.common.exception.processor;

import org.springframework.dao.CannotAcquireLockException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.orm.hibernate3.HibernateJdbcException;
import org.springframework.orm.hibernate3.HibernateObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException;
import org.springframework.orm.hibernate3.HibernateQueryException;
import org.springframework.orm.hibernate3.HibernateSystemException;

import com.maxjay.common.exception.ERR;
import com.maxjay.common.exception.GeneException;


/**
 * springframework的Hibernate异常转换
 * @author zhengmw
 *
 */
public class DataAccessExceptionProcessor {
	/**
	 * 转换异常
	 * 
	 * @param ex
	 * @return
	 */
	public static GeneException convertDataAccessException(DataAccessException ex) {
		// HibernateAccessException 异常对应的DataAccessException
		if (ex instanceof DataAccessResourceFailureException) {
			return GeneException.getGeneException(ERR.DB_CONNECTION_REEOR, ex);
		}
		if (ex instanceof DataIntegrityViolationException) {
			return GeneException.getGeneException(ERR.DB_CONSTRAINT_VIOLATION_REEOR, ex);
		}
		if (ex instanceof CannotAcquireLockException) {
			return GeneException.getGeneException(ERR.DB_ACQUIRE_LOCK_REEOR, ex);
		}
		if (ex instanceof HibernateJdbcException) {
			return GeneException.getGeneException(ERR.DB_JDBC_REEOR, ex);
		}
		if (ex instanceof HibernateQueryException) {
			return GeneException.getGeneException(ERR.DB_QUERY_REEOR, ex);
		}
		if (ex instanceof InvalidDataAccessApiUsageException) {
			return GeneException.getGeneException(ERR.DB_DATA_ACCESS_APIUSAGE_REEOR, ex);
		}
		if (ex instanceof HibernateObjectRetrievalFailureException) {
			return GeneException.getGeneException(ERR.DB_OBJECT_RETRIEVAL_FAILURE_REEOR, ex);
		}
		if (ex instanceof EmptyResultDataAccessException) {
			return GeneException.getGeneException(ERR.DB_NON_DATA_REEOR, ex);
		}
		if (ex instanceof IncorrectResultSizeDataAccessException) {
			return GeneException.getGeneException(ERR.DB_NON_UNIQUE_RESULT_REEOR, ex);
		}
		if (ex instanceof HibernateOptimisticLockingFailureException) {
			return GeneException
					.getGeneException(ERR.DB_OPTIMISTIC_LOCKING_FAILURE_REEOR, ex);
		}
		if (ex instanceof HibernateSystemException) {
			return GeneException.getGeneException(ERR.DB_HIBERNATE_RESOURCE_REEOR, ex);
		}

		// SQLException 异常对应的DataAccessException
		// TODO 其他等待扩充

		// fallback
		return GeneException.getGeneException(ERR.DB_ERROR, ex);
	}
}
